import { computed, reactive, onUnmounted } from "vue";
import { useStore as useUserStore } from "@/store/user";
import { $getredirectUrl, $getUserInfo, $loginAuth, $getCaptcha, $getMobileCode, $tripartiteMobile } from "@/apis/api";
import to from "await-to-js";
import { showToast } from "@nutui/nutui";
import { getUrlCode } from "@/common/util";
export default () => {
  const userStore = useUserStore();

  // 注册状态管理
  const register = reactive({
    // 是否显示
    is_show: false,
    // 手机号
    mobile: '',
    // 手机动态码key
    key: '',
    // 图文验证码输入框
    vercode: '',
    // 图文验证图片
    captcha: {
      index_code: '',
      img: '',
    },
    // 手机动态码
    dynacode: '',
    // 发送动态码状态
    dynacodeData: {
      // 倒计时
      seconds: 0,
      timer: null,
    } as any,
  });

  // 需要登陆
  const needLogin = computed(() => {
    return userStore.notLogin;
  })

  // 是否有open_id
  const has_open_id = computed(() => {
    return !!userStore.user_info.open_id;
  })

  // 获取openid使用的code
  const code = getUrlCode().code;
  // 登录状态管理
  const loginState = reactive({
    // 跳转地址
    redirectUrl: '',
  })

  // 执行登录
  const toLogin = () => {
    if (has_open_id.value) {
      getToken();
    } else {
      if (!code) {
        location.href = loginState.redirectUrl;
      }
    }
  }

  // 获取token
  const getToken = async () => {
    const [err, res]: any = await to($loginAuth({
      wx_openid: userStore.user_info.open_id,
      avatarUrl: userStore.user_info.avatarUrl,
      nickname: userStore.user_info.nickName,
    }))
    if (!err) {
      userStore.setLoginInfo({
        token: res.data.token,
        uid: res.data.uid,
      })
    }
  }

  // 获取图文验证码
  const getCaptcha = () => {
    $getCaptcha({}).then((res: any) => {
      register.captcha.img = res.data.img || '';
      register.captcha.index_code = res.data.index_code || '';
    })
  }
  // 发送手机动态码
  const sendMobileCode = () => {
    if (register.dynacodeData.seconds > 0) {
      return;
    }
    let params = {
      mobile: register.mobile,
      index_code: register.captcha.index_code,
      code: register.vercode,
      keywords: 'MOBILE_VERIFY_CODE',
    };
    if (!params.mobile) {
      showToast.fail('请输入手机号');
      return;
    }
    if (!params.code) {
      showToast.fail('请输入验证码');
      return;
    }
    $getMobileCode(params).then((res: any) => {
      showToast.success('发送成功!');
      register.key = res.data.key || '';
      register.dynacodeData.seconds = 120;
      register.dynacodeData.timer = setInterval(() => {
        if (register.dynacodeData.seconds > 0) {
          register.dynacodeData.seconds--;
        } else {
          clearInterval(register.dynacodeData.timer);
        }
      }, 1000)
    })
  }
  // 绑定手机号
  const forceBindMobile = () => {
    let params = {
      mobile: register.mobile,
      key: register.key,
      code: register.dynacode,
      wx_openid: userStore.user_info.open_id,
    }
    if (!params.mobile) {
      showToast.fail("请输入手机号!")
      return;
    }
    if (!params.code) {
      showToast.fail("请输入动态码!")
      return;
    }
    $tripartiteMobile(params).then((res: any) => {
      showToast.success("登录成功!");
      userStore.setLoginInfo({
        token: res.data.token,
        uid: res.data.uid,
      })
      register.is_show = false;
    })
  }
  // 获取用户openid
  const getOpenId = async ({ redirect }: { redirect: boolean } = { redirect: false }) => {
    // 没有openid
    if (!has_open_id.value) {
      if (!code) {
        const local = window.location.href;
        const [err, res]: any = await to($getredirectUrl({
          scope: "snsapi_userinfo",
          redirect_url: local,
        }));
        if (!err) {
          loginState.redirectUrl = res.data.url;
          if (redirect) {
            location.href = loginState.redirectUrl;
          }
        }
      } else {
        const [err, res]: any = await to($getUserInfo({
          code,
        }));
        if (!err) {
          await userStore.setUserInfo({ open_id: res.data?.openid || '', avatarUrl: res.data?.userinfo?.avatarUrl || '', nickName: res.data?.userinfo?.nickName || '' });
        }
      }
    }
  }
  // 获取用户token(失败准备登录流程)
  const getAuth = async () => {
    // 没有token
    if (needLogin.value) {
      await getOpenId();
      if (userStore.user_info.open_id) {
        getToken();
      }
    }
  }

  onUnmounted(() => {
    clearInterval(register.dynacodeData.timer);
  })

  return {
    userStore,
    register,
    needLogin,
    has_open_id,
    toLogin,
    getCaptcha,
    sendMobileCode,
    forceBindMobile,
    getAuth,
    getOpenId,
    getUrlCode,
  }
}